﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace TlvLib.SiChuan
{
    class TlvWriter
    {

        public static void Write(Stream stream, TvPacket packet, bool flush = true)
        {
            var memStream = new MemoryStream();

            //tag
            var buffer = Configuration.EndianBitConverter.GetBytes(ProtocolConstant.Tag);
            WriteAllBytes(memStream, buffer);

            //length
            var len = 2 + 6 + packet.Value.Length + 4;
            buffer = Configuration.EndianBitConverter.GetBytes(len);
            WriteAllBytes(memStream, buffer);

            //type
            buffer = Configuration.EndianBitConverter.GetBytes((short) packet.Type);
            WriteAllBytes(memStream, buffer);

            //ver
            buffer = Configuration.TextEncoding.GetBytes(ProtocolConstant.Ver);
            WriteAllBytes(memStream, buffer);

            //value
            WriteAllBytes(memStream, packet.Value);

            //ending
            buffer = Configuration.EndianBitConverter.GetBytes(ProtocolConstant.Ending);
            WriteAllBytes(memStream, buffer);

            var memBuf = memStream.ToArray();
            stream.Write(memBuf, 0, memBuf.Length);

            if (flush)
            {
                stream.Flush();
            }

        }

        private static void WriteAllBytes(Stream stream, byte[] buffer)
        {
            stream.Write(buffer, 0, buffer.Length);
        }
    }
}
